package mqtt

import (
	"gitee.com/sansaniot/ssiot-core/logger"
	"github.com/bytedance/sonic"
	mqtt "github.com/eclipse/paho.mqtt.golang"

	"ssalarm/common/constant"
	"ssalarm/common/enums"
	"ssalarm/internal/data/partition"
)

// 消息订阅处理
func TopicHandler(c mqtt.Client, message mqtt.Message) {
	logger.Debugf("订阅到主题%s, 消息%s", message.Topic(), string(message.Payload()))
	// 获取处理对象
	var bp partition.BaseDataDealer
	if message.Topic() == constant.HandledMsgTopic {
		bp = partition.GetPartialServe(enums.Handler.Get().Name)
	} else if message.Topic() == constant.DeviceDeleteMsgTopic ||
		message.Topic() == constant.DeviceAddMsgTopic {
		bp = partition.GetPartialServe(enums.Broadcast.Get().Name)
	}
	//判断是否有效
	if bp == nil {
		return
	}
	var jsonData map[string]interface{}
	if err := sonic.Unmarshal(message.Payload(), &jsonData); err != nil {
		logger.Error(err)
		return
	}
	bp.Execute(message.Topic(), jsonData)
}
